<template>
  <div class="device-list">
    <el-card>
      <div slot="header">
        <span>设备列表</span>
        <el-button style="float: right;" type="primary" @click="fetchDevices" :loading="loading" aria-label="刷新设备列表" title="刷新设备列表">刷新</el-button>
      </div>
      <el-alert v-if="error" :title="error" type="error" show-icon></el-alert>
      <el-table :data="devices" style="width: 100%" v-loading="loading" aria-label="设备列表" title="设备列表">
        <el-table-column prop="device_id" label="设备ID"></el-table-column>
        <el-table-column prop="name" label="设备名称"></el-table-column>
        <el-table-column prop="type" label="设备类型"></el-table-column>
        <el-table-column prop="status" label="设备状态"></el-table-column>
        <el-table-column prop="room" label="所在房间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" aria-label="编辑设备" title="编辑设备">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)" aria-label="删除设备" title="删除设备">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 编辑设备对话框 -->
    <el-dialog title="编辑设备" :visible.sync="editDialogVisible" width="40%" aria-label="编辑设备对话框">
      <el-form :model="editingDevice" label-width="100px">
        <el-form-item label="设备ID">
          <el-input v-model="editingDevice.device_id" name="edit_device_id" disabled placeholder="设备ID" aria-label="设备ID" title="设备ID"></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="editingDevice.name" name="edit_name" placeholder="请输入设备名称" aria-label="设备名称" title="设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="editingDevice.type" name="edit_type" placeholder="请选择设备类型" aria-label="设备类型" title="设备类型">
            <el-option label="传感器" value="sensor"></el-option>
            <el-option label="控制器" value="controller"></el-option>
            <el-option label="执行器" value="actuator"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="editingDevice.status" name="edit_status" placeholder="请选择设备状态" aria-label="设备状态" title="设备状态">
            <el-option label="在线" value="1"></el-option>
            <el-option label="离线" value="0"></el-option>
            <el-option label="故障" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在房间">
          <el-input v-model="editingDevice.room" name="edit_room" placeholder="请输入所在房间" aria-label="所在房间" title="所在房间"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" aria-label="取消编辑" title="取消编辑">取 消</el-button>
        <el-button type="primary" @click="saveEdit" aria-label="保存设备信息" title="保存设备信息">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllDevices, updateDevice, deleteDeviceById } from '../../services/device.js'

export default {
  name: 'DeviceList',
  data() {
    return {
      devices: [],
      loading: false,
      error: '',
      editDialogVisible: false,
      editingDevice: {
        id: '',
        device_id: '',
        name: '',
        type: '',
        status: '',
        room: ''
      }
    }
  },
  mounted() {
    this.fetchDevices()
  },
  methods: {
    async fetchDevices() {
      this.loading = true
      this.error = ''
      try {
        const response = await getAllDevices()
        console.log('设备列表响应:', response)
        // 确保响应是数组格式，如果返回的是对象但包含数据数组，则提取该数组
        if (Array.isArray(response)) {
          this.devices = response
        } else if (response && typeof response === 'object' && Array.isArray(response.data)) {
          this.devices = response.data
        } else if (response && typeof response === 'object' && response.data && Array.isArray(response.data.data)) {
          this.devices = response.data.data
        } else {
          this.devices = []
        }
      } catch (error) {
        console.error('获取设备列表失败:', error)
        this.error = '无法连接到服务器，请检查网络连接或联系管理员'
        this.$message.error(this.error)
      } finally {
        this.loading = false
      }
    },
    handleEdit(row) {
      // 处理编辑逻辑
      this.editingDevice = { ...row }
      this.editDialogVisible = true
    },
    async saveEdit() {
      try {
        // 确保传递正确的对象结构
        const deviceData = {
          id: this.editingDevice.id,
          device_id: this.editingDevice.device_id,
          name: this.editingDevice.name,
          type: this.editingDevice.type,
          status: this.editingDevice.status,
          room: this.editingDevice.room
        }
        
        const response = await updateDevice(deviceData)
        // 检查响应
        if (response) {
          this.$message.success('更新设备成功')
          this.editDialogVisible = false
          this.fetchDevices() // 刷新列表
        } else {
          this.$message.error('更新设备失败')
        }
      } catch (error) {
        console.error('更新设备失败:', error)
        this.$message.error('无法连接到服务器，请检查网络连接或联系管理员')
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该设备吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 调用删除接口
        const response = await deleteDeviceById(row.device_id)
        // 检查响应
        if (response) {
          this.$message.success('删除成功')
          this.fetchDevices() // 刷新列表
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        // 用户取消删除或删除失败
        if (error !== 'cancel') {
          console.error('删除设备失败:', error)
          this.$message.error('无法连接到服务器，请检查网络连接或联系管理员')
        }
      }
    }
  }
}
</script>

<style scoped>
.device-list {
  padding: 20px;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  width: -webkit-fill-available;
  width: stretch;
}
</style>